package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.mapper.UserInfoMapper;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.pojo.LogPage;
import com.tanhua.manage.pojo.UserInfo;
import com.tanhua.manage.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LogPageService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public PageResult queryLogList(String page, String pageSize, String sortProp, String sortOrder, String type, String uid) {
        if(StringUtils.equals("logTime",sortProp)){
            sortProp = "active_time";
        }
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",uid).orderBy(true, StringUtils.equals("ascending",sortOrder),sortProp);
        Page<Log> logPage = new Page<>(Integer.parseInt(page),Integer.parseInt(pageSize));
        IPage<Log> logIPage = this.logMapper.selectPage(logPage, queryWrapper);
        List<Log> records = logIPage.getRecords();
        List<LogPage> logPageList = new ArrayList<>();
        for (Log record : records) {
            LogPage logPage1 = new LogPage();
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id",record.getUserId());
            UserInfo userInfo = this.userInfoMapper.selectOne(queryWrapper1);
            logPage1.setId(record.getId());
            logPage1.setPlace(userInfo.getCity());  //地点
            logPage1.setEquipment(record.getEquipment());  //设备
            logPage1.setLogTime(record.getActiveTime().getTime());  //开始登陆时间
            logPageList.add(logPage1);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(Integer.parseInt(page));
        pageResult.setCounts(Integer.valueOf(String.valueOf(logIPage.getTotal())));
        pageResult.setPagesize(Integer.parseInt(pageSize));
        pageResult.setPages(Integer.parseInt(String.valueOf(logIPage.getPages())));
        pageResult.setItems(logPageList);
        return pageResult;
    }
}
